package com.catering.service.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.catering.dao.CateringGroupBuyingDao;
import com.catering.dao.CateringGroupOrdersDao;
import com.catering.entity.CateringGroupBuying;
import com.catering.entity.CateringGroupOrders;
import com.catering.service.CateringGroupOrdersService;
import com.catering.until.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ScheduledService implements SchedulingConfigurer {
	
	@Value("${http.name}")
	private String httpName;

	@Autowired
	private CateringGroupBuyingDao cateringGroupBuyingDao;
	@Autowired
	private CateringGroupOrdersDao cateringGroupOrdersDao;

	private RestTemplate restTemplate=new RestTemplate();
	

	@Scheduled(cron = "0 0 0 * * ? ") //每天0点执行
	public void ordersSchedule(){
		doOrdersSchedule();
	}

	/**
	 * 检查开团是否结束
	 */
	private void doOrdersSchedule(){
		log.info("=====>>>>>定时执行检查开团是否截止开始  {}", CommonUtils.getTime(19));
		try{
			//查询小于当前时间且状态为未完成和默认提醒的便签数据
			List<CateringGroupBuying> groupBuyings = cateringGroupBuyingDao.selectList(new LambdaQueryWrapper<CateringGroupBuying>().eq(CateringGroupBuying::getStatus,1));
			List<CateringGroupBuying> overBuyings = new ArrayList<>();
			if(groupBuyings.isEmpty()) {
				log.info("暂无开团数据  {}",CommonUtils.getTime(19));
			}else{
				String nowTime = CommonUtils.getTime(19);
				for(CateringGroupBuying buying : groupBuyings){
					if(CommonUtils.dateDiff(nowTime,buying.getExpireTime(),"s") <= 0){
						buying.setStatus(3);
						overBuyings.add(buying);
					}
				}
				if(!overBuyings.isEmpty()){
					List<CateringGroupOrders> ordersList = cateringGroupOrdersDao.selectList(new LambdaQueryWrapper<CateringGroupOrders>().eq(CateringGroupOrders::getPayStatus,1).in(CateringGroupOrders::getGroupBuyingId,overBuyings.stream().map(CateringGroupBuying::getSysId).collect(Collectors.toList())));
					// 进行退款操作
					Map dataMap = new HashMap();
					for(CateringGroupOrders groupOrders : ordersList){
						dataMap.put("orderId",groupOrders.getSysId());
						String resultData = restTemplate.postForObject(httpName+"/wxapi/catering/api/refund",dataMap,String.class);
						JSONObject resp = (JSONObject) JSON.parse(resultData);
						if ("SUCCESS".equals(resp.get("result_code")) && "OK".equals(resp.get("return_msg"))) {
							// 将订单修改成退款状态
							groupOrders.setPayStatus(2);
							cateringGroupOrdersDao.updateById(groupOrders);
						}
					}
				}

			}
		}catch (Exception e){
			e.printStackTrace();
		}
		log.info("=====>>>>>定时执行检查开团是否截止结束  {}",CommonUtils.getTime(19));
	}

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
	}
}
